<template>
  <div class="document-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>文档管理</h2>
      <p>管理知识库中的文档，支持上传、编辑、删除等操作</p>
    </div>

    <!-- 操作栏 -->
    <div class="toolbar">
      <div class="left-actions">
        <!-- 知识库选择 -->
        <el-select v-model="selectedKnowledgeBaseId" placeholder="选择知识库" @change="handleKnowledgeBaseChange" style="width: 200px;">
          <el-option v-for="kb in knowledgeBases" :key="kb.knowledgeBaseId || kb.id" :label="kb.knowledgeBaseName" :value="kb.knowledgeBaseId || kb.id" />
        </el-select>
        <!-- 搜索框 -->
          <el-input
            v-model="searchKeyword"
          placeholder="搜索文档标题"
            @input="handleSearch"
          style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      <div class="right-actions">
        <!-- 上传文档按钮 -->
        <el-button type="primary" @click="showUploadDialog">
          <el-icon><Upload /></el-icon>
          上传文档
        </el-button>
        <!-- 批量上传按钮 -->
        <el-button type="success" @click="showBatchUploadDialog">
          <el-icon><FolderAdd /></el-icon>
          批量上传
          </el-button>
        </div>
      </div>

    <!-- 文档列表表格 -->
    <div class="table-wrapper">
      <el-table :data="filteredDocuments" class="centered-table" v-loading="loading" element-loading-text="加载中..." :empty-text="getEmptyText()">
      <!-- 文档标题列 -->
      <el-table-column prop="documentTitle" label="文档标题" width="20%" min-width="160" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="document-title">
            <el-input v-if="editingRowId === row.id" v-model="row.documentTitle" placeholder="请输入文档标题" size="small" />
            <el-tooltip v-else :content="row.documentTitle" placement="top">
              <span class="document-title-text">{{ row.documentTitle }}</span>
            </el-tooltip>
            </div>
          </template>
        </el-table-column>
      <!-- 文件名列 -->
      <el-table-column prop="documentFileName" label="文件名" width="18%" min-width="140" show-overflow-tooltip />
      <!-- 文件大小列 -->
      <el-table-column prop="documentFileSize" label="文件大小" width="8%" min-width="80" align="center">
        <template #default="{ row }">
          <el-tag type="info">{{ formatFileSize(row.documentFileSize) }}</el-tag>
          </template>
        </el-table-column>
      <!-- 访问级别列 -->
      <el-table-column prop="documentAccessLevel" label="访问级别" width="8%" min-width="70" align="center">
        <template #default="{ row }">
          <div v-if="editingRowId === row.id">
            <el-select v-model="row.documentAccessLevel" size="small">
              <el-option label="公开" value="public" />
              <el-option label="私有" value="private" />
            </el-select>
            </div>
          <el-tag v-else :type="row.documentAccessLevel === 'public' ? 'success' : 'warning'">
            {{ row.documentAccessLevel === 'public' ? '公开' : '私有' }}
          </el-tag>
          </template>
        </el-table-column>
      <!-- 上传时间列 -->
      <el-table-column prop="createdAt" label="上传时间" width="18%" min-width="140" align="center">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="18%" min-width="160" align="center">
        <template #default="{ row }">
            <div class="operation-buttons">
            <!-- 查看详情按钮 -->
            <el-button type="text" size="small" @click="viewDocument(row)">
                <el-icon><View /></el-icon>
              查看
              </el-button>
            <!-- 下载按钮 -->
            <el-button 
              type="text" 
              size="small" 
              @click="downloadDocument(row)"
              :disabled="row.isDownloading"
              :loading="row.isDownloading">
              <el-icon><Download /></el-icon>
              {{ row.isDownloading ? '下载中...' : '下载' }}
            </el-button>
            <!-- 删除按钮 -->
            <el-button 
              type="text" 
              size="small" 
              @click="deleteDocumentHandler(row)"
              style="color: #f56c6c;">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
            </div>
          </template>
        </el-table-column>
        </el-table>
      </div>
      
    <!-- 分页 -->
    <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
        layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

    <!-- 上传文档对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传文档" width="500px">
      <el-form :model="uploadForm" label-width="100px">
        <el-form-item label="文档标题" required>
          <el-input v-model="uploadForm.documentTitle" placeholder="请输入文档标题" />
        </el-form-item>
        <el-form-item label="知识库" required>
          <el-select v-model="uploadForm.knowledgeBaseId" placeholder="选择知识库" style="width: 100%;">
            <el-option v-for="kb in knowledgeBases" :key="kb.knowledgeBaseId || kb.id" :label="kb.knowledgeBaseName" :value="kb.knowledgeBaseId || kb.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择文件" required>
      <el-upload
            ref="uploadRef"
        :auto-upload="false"
            :show-file-list="true"
            :limit="1"
        :on-change="handleFileChange"
            :on-remove="handleFileRemove"
      >
            <el-button type="primary">选择文件</el-button>
        <template #tip>
              <div class="el-upload__tip">支持 txt, pdf, doc, docx 等格式文件</div>
        </template>
      </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpload" :loading="uploading">确定上传</el-button>
      </template>
    </el-dialog>

    <!-- 批量上传对话框 -->
    <el-dialog v-model="batchUploadDialogVisible" title="批量上传文档" width="600px">
      <el-form :model="batchUploadForm" label-width="100px">
        <el-form-item label="知识库" required>
          <el-select v-model="batchUploadForm.knowledgeBaseId" placeholder="选择知识库" style="width: 100%;">
            <el-option v-for="kb in knowledgeBases" :key="kb.knowledgeBaseId || kb.id" :label="kb.knowledgeBaseName" :value="kb.knowledgeBaseId || kb.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="访问级别" required>
          <el-radio-group v-model="batchUploadForm.documentAccessLevel">
            <el-radio label="public">公开</el-radio>
            <el-radio label="private">私有</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择文件" required>
          <el-upload
            ref="batchUploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :multiple="true"
            :on-change="handleBatchFileChange"
            :on-remove="handleBatchFileRemove"
          >
            <el-button type="primary">选择多个文件</el-button>
            <template #tip>
              <div class="el-upload__tip">可选择多个文件同时上传</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchUploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchUpload" :loading="batchUploading">确定上传</el-button>
      </template>
    </el-dialog>

    <!-- 文档详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="文档详情" width="600px">
      <div v-if="selectedDocumentDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="文档标题">{{ selectedDocumentDetail.documentTitle }}</el-descriptions-item>
          <el-descriptions-item label="文档文件名">{{ selectedDocumentDetail.documentFileName }}</el-descriptions-item>
          <el-descriptions-item label="文档类型">{{ selectedDocumentDetail.documentFileType }}</el-descriptions-item>
          <el-descriptions-item label="文件大小">{{ formatFileSize(selectedDocumentDetail.documentFileSize) }}</el-descriptions-item>
          <el-descriptions-item label="访问级别">
            <el-tag :type="selectedDocumentDetail.documentAccessLevel === 'public' ? 'success' : 'warning'">
              {{ selectedDocumentDetail.documentAccessLevel === 'public' ? '公开' : '私有' }}
              </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="上传时间">{{ formatDate(selectedDocumentDetail.createdAt) }}</el-descriptions-item>
        </el-descriptions>
            </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Upload, FolderAdd, View, Download, Edit, Delete, Check, Close, Refresh } from '@element-plus/icons-vue'
import {
  getDocumentList,
  getDocumentDetail,
  uploadDocument,
  batchUploadDocuments,
  updateDocument,
  updateDocumentPermissions,
  deleteDocument,
  reprocessDocument,
  DownloadDocument
} from '@/api/document'
import { getKnowledgeBaseList } from '@/api/knowledgeBase'

// 响应式数据
const documents = ref([])
const knowledgeBases = ref([])
const selectedKnowledgeBaseId = ref('')
const searchKeyword = ref('')
const loading = ref(false)
const editingRowId = ref(null)
const originalData = ref({})
// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 上传相关
const uploadDialogVisible = ref(false)
const uploading = ref(false)
const uploadForm = ref({
  documentTitle: '',
  knowledgeBaseId: '',
  file: null
})

// 批量上传相关
const batchUploadDialogVisible = ref(false)
const batchUploading = ref(false)
const batchUploadForm = ref({
  knowledgeBaseId: '',
  documentAccessLevel: 'private',
  files: []
})

// 详情对话框
const detailDialogVisible = ref(false)
const selectedDocumentDetail = ref(null)

// 搜索防抖
let searchTimer = null

// 计算属性 - 过滤文档
const filteredDocuments = computed(() => {
  // 确保 documents.value 是数组
  if (!Array.isArray(documents.value)) {
    console.warn('documents.value 不是数组:', documents.value)
    return []
  }
  
  if (!searchKeyword.value) {
    return documents.value
  }
  
  return documents.value.filter(doc => {
    if (!doc || !doc.documentTitle) return false
    return doc.documentTitle.toLowerCase().includes(searchKeyword.value.toLowerCase())
  })
})

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '0 B'
  
  // 处理字符串类型的字节数
  if (typeof bytes === 'string') {
    bytes = parseInt(bytes, 10)
    if (isNaN(bytes)) return '未知'
  }
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  // 确保索引在有效范围内
  if (i < 0) return '0 B'
  if (i >= sizes.length) return '超大文件'
  
  const size = bytes / Math.pow(k, i)
  
  // 根据大小调整小数位数
  let precision = 2
  if (size >= 100) precision = 0
  else if (size >= 10) precision = 1
  
  return size.toFixed(precision) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  
  try {
    // 处理不同的日期格式
    let date
    if (typeof dateStr === 'string') {
      // 如果是ISO格式的字符串，直接创建Date对象
      if (dateStr.includes('T') || dateStr.includes('Z')) {
        date = new Date(dateStr)
      } else {
        // 处理其他格式的日期字符串
        date = new Date(dateStr.replace(/-/g, '/'))
      }
    } else if (dateStr instanceof Date) {
      date = dateStr
    } else {
      date = new Date(dateStr)
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '-'
    }
    
    // 格式化为中文日期时间
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    console.error('日期格式化错误:', e, '原始值:', dateStr)
    return '-'
  }
}

// 获取空状态文本
const getEmptyText = () => {
  if (!selectedKnowledgeBaseId.value) {
    return '请先选择知识库'
  }
  if (searchKeyword.value) {
    return '没有找到匹配的文档'
  }
  return '暂无文档'
}

// 加载知识库列表
const loadKnowledgeBases = async () => {
  console.log('尝试加载真实知识库数据')
  try {
    const res = await getKnowledgeBaseList({ page: 1, size: 100 })
    console.log('知识库API响应成功:', res)
    
    // 尝试多种可能的数据结构
    let kbData = []
    if (res && res.data && Array.isArray(res.data)) {
      kbData = res.data
    } else if (res && res.content && Array.isArray(res.content)) {
      kbData = res.content
    } else if (res && res.result && Array.isArray(res.result)) {
      kbData = res.result
    } else if (Array.isArray(res)) {
      kbData = res
    }
    
    // 如果有有效数据，更新知识库列表
    if (kbData.length > 0) {
      console.log('更新知识库数据:', kbData)
      // 标准化字段，确保包含 knowledgeBaseId
      knowledgeBases.value = kbData.map(item => ({
        ...item,
        knowledgeBaseId: item.knowledgeBaseId || item.id || item.knowledgebaseId || item.knowledgeBaseId,
        id: item.id || item.knowledgeBaseId
      }))
      // 如果当前选择的知识库不在新列表中，选择第一个
      const currentExists = knowledgeBases.value.find(kb => (kb.knowledgeBaseId || kb.id) === selectedKnowledgeBaseId.value)
      if (!currentExists) {
        selectedKnowledgeBaseId.value = knowledgeBases.value[0].knowledgeBaseId || knowledgeBases.value[0].id
        console.log('更新选择的知识库:', selectedKnowledgeBaseId.value)
      }
      // 重新加载文档
      loadDocuments()
    } else {
      console.log('API返回空数据')
      ElMessage.warning('知识库列表为空，请先创建知识库')
    }
  } catch (error) {
    console.error('加载知识库失败:', error)
    ElMessage.error(`加载知识库失败: ${error.message || '网络错误'}`)
  }
}

// 加载文档列表
const loadDocuments = async () => {
  console.log('尝试加载文档数据, 知识库ID:', selectedKnowledgeBaseId.value)
  if (!selectedKnowledgeBaseId.value) {
    console.log('没有选择知识库')
    ElMessage.warning('请先选择知识库')
    return
  }
  
  loading.value = true
  try {
    const res = await getDocumentList(selectedKnowledgeBaseId.value, {
      page: currentPage.value,
      size: pageSize.value
    })
    console.log('文档API响应成功:', res)
    
    // 尝试多种可能的数据结构
    let docData = []
    let totalCount = 0
    
    if (res && res.data && Array.isArray(res.data)) {
      docData = res.data
      totalCount = res.total || res.count || docData.length
    } else if (res && res.content && Array.isArray(res.content)) {
      docData = res.content
      totalCount = res.totalElements || res.total || res.count || docData.length
    } else if (res && res.result && Array.isArray(res.result)) {
      docData = res.result
      totalCount = res.total || res.count || docData.length
    } else if (Array.isArray(res)) {
      docData = res
      totalCount = docData.length
    }
    
    // 如果有有效数据，更新文档列表
    if (docData.length > 0) {
      console.log('更新文档数据:', docData)
      documents.value = docData
      total.value = totalCount
    } else {
      console.log('API返回空数据')
      documents.value = []
      total.value = 0
      ElMessage.info('当前知识库暂无文档')
    }
  } catch (error) {
    console.error('加载文档失败:', error)
    ElMessage.error(`加载文档失败: ${error.message || '网络错误'}`)
    documents.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理知识库变更
const handleKnowledgeBaseChange = () => {
  currentPage.value = 1
  loadDocuments()
}

// 处理搜索
const handleSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    // 搜索在前端进行过滤
  }, 300)
}

// 显示上传对话框
const showUploadDialog = () => {
  if (!selectedKnowledgeBaseId.value) {
    ElMessage.warning('请先选择知识库')
    return
  }
  uploadForm.value = {
    documentTitle: '',
    knowledgeBaseId: selectedKnowledgeBaseId.value,
    file: null
  }
  uploadDialogVisible.value = true
}

// 显示批量上传对话框
const showBatchUploadDialog = () => {
  if (!selectedKnowledgeBaseId.value) {
    ElMessage.warning('请先选择知识库')
    return
  }
  batchUploadForm.value = {
    knowledgeBaseId: selectedKnowledgeBaseId.value,
    documentAccessLevel: 'private',
    files: []
  }
  batchUploadDialogVisible.value = true
}

// 处理文件选择
const handleFileChange = (file) => {
  uploadForm.value.file = file.raw
  if (!uploadForm.value.documentTitle) {
    uploadForm.value.documentTitle = file.name.split('.')[0]
  }
}

// 处理文件移除
const handleFileRemove = () => {
  uploadForm.value.file = null
}

// 处理批量文件选择
const handleBatchFileChange = (file, fileList) => {
  batchUploadForm.value.files = fileList.map(f => f.raw)
}

// 处理批量文件移除
const handleBatchFileRemove = (file, fileList) => {
  batchUploadForm.value.files = fileList.map(f => f.raw)
}

// 处理上传
const handleUpload = async () => {
  if (!uploadForm.value.documentTitle || !uploadForm.value.knowledgeBaseId || !uploadForm.value.file) {
    ElMessage.warning('请填写完整信息')
    return
  }

  // 检查文件大小
  const maxSize = 50 * 1024 * 1024 // 50MB
  if (uploadForm.value.file.size > maxSize) {
    ElMessage.error('文件大小不能超过50MB')
    return
  }



  uploading.value = true
  try {
    console.log('开始上传文件:', {
      documentTitle: uploadForm.value.documentTitle,
      knowledgeBaseId: uploadForm.value.knowledgeBaseId,
      fileName: uploadForm.value.file.name,
      fileSize: uploadForm.value.file.size,
      fileType: uploadForm.value.file.type
    })

    await uploadDocument(uploadForm.value)
    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    loadDocuments()
  } catch (error) {
    console.error('上传失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      status: error.response?.status,
      data: error.response?.data
    })
    
    // 根据错误类型显示不同的错误信息
    if (error.response?.status === 413) {
      ElMessage.error('文件太大，请选择较小的文件')
    } else if (error.response?.status === 415) {
      ElMessage.error('不支持的文件格式')
    } else if (error.response?.status === 401) {
      ElMessage.error('请先登录')
    } else if (error.response?.status === 403) {
      ElMessage.error('没有权限上传文档')
    } else if (error.response?.status === 400) {
      ElMessage.error(`上传失败: ${error.response.data?.message || '请求参数错误'}`)
    } else if (error.code === 'NETWORK_ERROR') {
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      ElMessage.error(`上传失败: ${error.message || '未知错误'}`)
    }
  } finally {
    uploading.value = false
  }
}

// 处理批量上传
const handleBatchUpload = async () => {
  if (!batchUploadForm.value.knowledgeBaseId || batchUploadForm.value.files.length === 0) {
    ElMessage.warning('请选择知识库和文件')
    return
  }

  // 检查文件
  const maxSize = 50 * 1024 * 1024 // 50MB
  const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain']
  
  for (let i = 0; i < batchUploadForm.value.files.length; i++) {
    const file = batchUploadForm.value.files[i]
    if (file.size > maxSize) {
      ElMessage.error(`文件 "${file.name}" 太大，不能超过50MB`)
      return
    }
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error(`文件 "${file.name}" 格式不支持，请上传PDF、DOC、DOCX或TXT文件`)
      return
    }
  }

  batchUploading.value = true
  try {
    console.log('开始批量上传文件:', {
      knowledgeBaseId: batchUploadForm.value.knowledgeBaseId,
      documentAccessLevel: batchUploadForm.value.documentAccessLevel,
      fileCount: batchUploadForm.value.files.length,
      files: batchUploadForm.value.files.map(f => ({
        name: f.name,
        size: f.size,
        type: f.type
      }))
    })

    await batchUploadDocuments(batchUploadForm.value)
    ElMessage.success('批量上传成功')
    batchUploadDialogVisible.value = false
    loadDocuments()
  } catch (error) {
    console.error('批量上传失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      status: error.response?.status,
      data: error.response?.data
    })
    
    // 根据错误类型显示不同的错误信息
    if (error.response?.status === 413) {
      ElMessage.error('文件太大，请选择较小的文件')
    } else if (error.response?.status === 415) {
      ElMessage.error('不支持的文件格式')
    } else if (error.response?.status === 401) {
      ElMessage.error('请先登录')
    } else if (error.response?.status === 403) {
      ElMessage.error('没有权限上传文档')
    } else if (error.response?.status === 400) {
      ElMessage.error(`批量上传失败: ${error.response.data?.message || '请求参数错误'}`)
    } else if (error.code === 'NETWORK_ERROR') {
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      ElMessage.error(`批量上传失败: ${error.message || '未知错误'}`)
    }
  } finally {
    batchUploading.value = false
  }
}

// 查看文档详情
const viewDocument = async (document) => {
  try {
    // 使用正确的文档ID字段
    const documentId = document.documentId || document.id
    if (!documentId) {
      ElMessage.error('文档ID不存在')
      return
    }

    const res = await getDocumentDetail(documentId)
    console.log(res.data);
    
    selectedDocumentDetail.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取文档详情失败:', error)
    ElMessage.error('获取文档详情失败')
  }
}

// 下载文档
const downloadDocument = async (doc) => {
  // 防止重复点击
  if (doc.isDownloading) {
    return
  }
  
  try {
    // 设置下载状态
    doc.isDownloading = true
    
    console.log('下载文档信息:', doc);
    
    // 使用正确的文档ID字段
    const documentId = doc.documentId || doc.id
    if (!documentId) {
      ElMessage.error('文档ID不存在')
      return
    }
    
    let res = await DownloadDocument(documentId)
    console.log('下载响应:', res.data);
    
    // 创建临时下载链接
    const url = window.URL.createObjectURL(res.data)
    const link = window.document.createElement('a')
    link.href = url
    
    // 优先使用documentFileName，如果没有则使用documentTitle，最后使用默认名称
    let downloadFileName = doc.documentFileName || doc.documentTitle || 'document'
    
    // 确保文件名有正确的扩展名
    if (!downloadFileName.includes('.')) {
      // 根据文件类型添加扩展名
      const contentType = res.data.type || ''
      if (contentType.includes('pdf')) {
        downloadFileName += '.pdf'
      } else if (contentType.includes('word') || contentType.includes('docx')) {
        downloadFileName += '.docx'
      } else if (contentType.includes('doc')) {
        downloadFileName += '.doc'
      } else if (contentType.includes('text')) {
        downloadFileName += '.txt'
      } else {
        downloadFileName += '.file'
      }
    }
    
    link.download = downloadFileName
    console.log('下载文件名:', downloadFileName)
    
    window.document.body.appendChild(link)
    link.click()
    window.document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success(`下载成功: ${downloadFileName}`)
    
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  } finally {
    // 重置下载状态
    doc.isDownloading = false
  }
}




// 删除文档
const deleteDocumentHandler = async (document) => {
  try {
    await ElMessageBox.confirm(`确定要删除文档"${document.documentTitle}"吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 使用正确的文档ID字段
    const documentId = document.documentId || document.id
    if (!documentId) {
      ElMessage.error('文档ID不存在')
      return
    }

    await deleteDocument(documentId)
    ElMessage.success('删除成功')
    loadDocuments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  loadDocuments()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadDocuments()
}

// 组件挂载
onMounted(() => {
  console.log('DocumentManagement 组件挂载')
  
  // 立即加载真实数据
  loadKnowledgeBases().catch(error => {
    console.error('加载真实数据失败:', error)
    ElMessage.error('初始化失败，请刷新页面重试')
  })
})

// 组件卸载
onUnmounted(() => {
  clearTimeout(searchTimer)
})
</script>

<style scoped>
.document-management {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  box-sizing: border-box;
  width: 100%;
  max-width: 100%;
}

.page-header {
  margin-bottom: 32px;
  background: rgba(255, 255, 255, 0.95);

  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 100%;
  max-width: 1400px;
  margin: 0 auto 32px auto;
  align-self: center;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 12px 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-align: center;
}

.page-header p {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
  line-height: 1.6;
  text-align: center;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 20px;
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 100%;
  max-width: 1400px;
  margin: 0 auto 24px auto;
  align-self: center;
  box-sizing: border-box;
}

.left-actions,
.right-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.left-actions .el-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.left-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.right-actions .el-input {
  border-radius: 8px;
  border: 1px solid #e1e8ed;
  transition: all 0.3s ease;
}

.right-actions .el-input:focus-within {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 表格容器 */
.table-wrapper {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto 24px auto;
  align-self: center;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}

.el-table {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-width: 100%;
  width: 100%;
  margin: 0 auto;
  align-self: center;
  box-sizing: border-box;
}

.el-table th {
  background: #f8fafc !important;
  color: #374151 !important;
  font-weight: 600;
  border: none;
  border-bottom: 2px solid #e5e7eb;
  padding: 16px 12px;
  font-size: 14px;
}

.el-table td {
  border-bottom: 1px solid #f0f2f5;
  padding: 16px 12px;
  transition: all 0.3s ease;
}

.el-table tr:hover td {
  background: #f9fafb;
  transform: none;
}

.document-title-text {
  display: inline-block;
  max-width: 280px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 500;
  color: #2c3e50;
}

.operation-buttons {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
  min-width: 150px;
}

.operation-buttons .el-button {
  border-radius: 6px;
  padding: 4px 8px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.operation-buttons .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.operation-buttons .el-button .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

/* 标签样式 */
.el-tag {
  border-radius: 6px;
  font-weight: 500;
  padding: 4px 8px;
}

.el-tag--info {
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  color: white;
  border: none;
}

.el-tag--success {
  background: linear-gradient(135deg, #00b894 0%, #00a085 100%);
  color: white;
  border: none;
}

.el-tag--warning {
  background: linear-gradient(135deg, #fdcb6e 0%, #e17055 100%);
  color: white;
  border: none;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 24px;
  background: rgba(255, 255, 255, 0.95);
  padding: 4px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 100%;
  max-width: 1400px;
  margin: 24px auto;
  align-self: center;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f2f5;
}

/* 描述列表样式 */
:deep(.el-descriptions) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-descriptions__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px 20px;
}

:deep(.el-descriptions__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-descriptions__body) {
  background: white;
}

:deep(.el-descriptions__label) {
  background: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-descriptions__content) {
  color: #34495e;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .document-management {
    padding: 16px;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 16px;
  }
  
  .left-actions,
  .right-actions {
    width: 100%;
    justify-content: center;
  }
  
  .operation-buttons {
    gap: 4px;
    min-width: auto;
    flex-direction: column;
  }
  
  .operation-buttons .el-button {
    padding: 4px 8px;
    font-size: 11px;
    width: 100%;
  }
  
  /* 确保表格在小屏幕上可以水平滚动 */
  :deep(.el-table) {
    overflow-x: auto;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header,
.toolbar,
.el-table,
.pagination-container {
  animation: fadeInUp 0.6s ease-out;
}

/* 滚动条样式 */
:deep(::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

/* 表格样式 */
:deep(.el-table) {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  max-width: 100%;
  width: 100% !important;
  table-layout: fixed !important;
  box-sizing: border-box !important;
}

/* 确保表格列铺满整个宽度 */
:deep(.el-table__body),
:deep(.el-table__header) {
  width: 100% !important;
  table-layout: fixed !important;
}

:deep(.el-table__body-wrapper),
:deep(.el-table__header-wrapper) {
  width: 100% !important;
  overflow-x: hidden !important;
}

/* 表格列样式 - 严格宽度控制 */
:deep(.el-table .el-table__cell) {
  width: auto !important;
  min-width: 0 !important;
  max-width: 100% !important;
  padding: 8px 4px !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
  box-sizing: border-box !important;
  word-break: break-all !important;
}

/* 设置各列的严格宽度比例 */
:deep(.el-table .el-table__cell:nth-child(1)) {
  width: 20% !important; /* 文档标题列 */
  max-width: 20% !important;
  min-width: 0 !important;
}

:deep(.el-table .el-table__cell:nth-child(2)) {
  width: 18% !important; /* 文件名列 */
  max-width: 18% !important;
  min-width: 0 !important;
}

:deep(.el-table .el-table__cell:nth-child(3)) {
  width: 8% !important; /* 文件大小列 */
  max-width: 8% !important;
  min-width: 0 !important;
}

:deep(.el-table .el-table__cell:nth-child(4)) {
  width: 8% !important; /* 访问级别列 */
  max-width: 8% !important;
  min-width: 0 !important;
}

:deep(.el-table .el-table__cell:nth-child(5)) {
  width: 18% !important; /* 上传时间列 */
  max-width: 18% !important;
  min-width: 0 !important;
}

:deep(.el-table .el-table__cell:nth-child(6)) {
  width: 18% !important; /* 操作列 */
  max-width: 18% !important;
  min-width: 0 !important;
}

/* 确保表格内容不超出 - 强制文本处理 */
:deep(.el-table .cell) {
  width: 100% !important;
  max-width: 100% !important;
  min-width: 0 !important;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  word-break: break-all !important;
  word-wrap: normal !important;
  box-sizing: border-box !important;
  display: block !important;
}

/* 表格头部样式 */
:deep(.el-table th) {
  background: #f8fafc !important;
  color: #374151 !important;
  font-weight: 600;
  border: none;
  border-bottom: 2px solid #e5e7eb;
  padding: 8px 4px;
  font-size: 14px;
  width: auto !important;
  max-width: 100% !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
  box-sizing: border-box !important;
}

/* 表格行样式 */
:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  padding: 8px 4px;
  transition: all 0.3s ease;
  width: auto !important;
  max-width: 100% !important;
  overflow: hidden !important;
  box-sizing: border-box !important;
}

:deep(.el-table tr:hover td) {
  background: #f9fafb;
  transform: none;
}

/* 确保表格容器完全铺满 */
.table-wrapper {
  width: 100% !important;
  max-width: 100% !important;
  overflow: hidden !important;
  box-sizing: border-box !important;
}

.centered-table {
  width: 100% !important;
  max-width: 100% !important;
  margin: 0 auto !important;
  display: block !important;
  box-sizing: border-box !important;
  overflow: hidden !important;
}

/* 表格内部元素完全铺满 */
:deep(.el-table__inner-wrapper) {
  width: 100% !important;
  max-width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
  table-layout: fixed !important;
}

:deep(.el-table__header) {
  width: 100% !important;
  table-layout: fixed !important;
}

/* 确保表格行铺满 */
:deep(.el-table__row) {
  width: 100% !important;
}

/* 表格单元格内容铺满 */
:deep(.el-table .cell) {
  width: 100% !important;
  box-sizing: border-box !important;
}

/* 操作按钮区域铺满 */
.operation-buttons {
  width: 100% !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  gap: 8px !important;
}

/* 强制表格布局固定，防止内容超出 */
:deep(.el-table) {
  table-layout: fixed !important;
  width: 100% !important;
  max-width: 100% !important;
}

/* 确保表格行和单元格完全适应 */
:deep(.el-table__row) {
  width: 100% !important;
  table-layout: fixed !important;
}

:deep(.el-table__cell) {
  box-sizing: border-box !important;
  word-break: break-all !important;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}

/* 特殊处理长文本内容 */
:deep(.document-title) {
  max-width: 100% !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
  display: block !important;
  box-sizing: border-box !important;
}

:deep(.el-tag) {
  max-width: 100% !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
  display: inline-block !important;
  box-sizing: border-box !important;
  font-size: 12px !important;
  padding: 2px 6px !important;
}

/* 操作按钮区域严格控制 */
.operation-buttons {
  width: 100% !important;
  max-width: 100% !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  gap: 4px !important;
  box-sizing: border-box !important;
}

.operation-buttons .el-button {
  font-size: 12px !important;
  padding: 4px 8px !important;
  min-width: auto !important;
  max-width: 100% !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
}

/* 确保表格不会产生水平滚动条 */
:deep(.el-table__body-wrapper) {
  overflow-x: hidden !important;
}

:deep(.el-table__header-wrapper) {
  overflow-x: hidden !important;
}

/* 表格容器严格控制 */
.table-wrapper {
  width: 100% !important;
  max-width: 100% !important;
  overflow: hidden !important;
  box-sizing: border-box !important;
}

.centered-table {
  width: 100% !important;
  max-width: 100% !important;
  margin: 0 auto !important;
  display: block !important;
  box-sizing: border-box !important;
  overflow: hidden !important;
}

/* 强制所有表格元素适应宽度 */
:deep(.el-table *),
:deep(.el-table__inner-wrapper *),
:deep(.el-table__body *),
:deep(.el-table__header *) {
  box-sizing: border-box !important;
  max-width: 100% !important;
}
</style>